#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<vector>
#include<string>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void Write(int wfd)
{
    string s="hello child";
    pid_t pid=getpid();
    int number=0;

    char buf[1024];
    while(true)
    {
        sleep(1);
        //构建字符串进行发送   snprintf的使用
        snprintf(buf,sizeof(buf),"%s-%d-%d",s.c_str(),pid,number++);
        cout<<buf<<endl;
        write(wfd,buf,strlen(buf));
    }
}

void Read(int rfd)
{
    char buf[1024];
    while(true)
    {
        ssize_t n=read(rfd,buf,sizeof(buf));
        if(n>0)
        {
            buf[n]=0;
            cout<<"father get message["<<getpid()<<"]#"<<buf<<endl;
        }
        else if(n==0)
        {
            cout<<"father get null message"<<endl;
            return ;
        }
        else return ;

    }
}

int main()
{
    int pipefd[2]={0};
    int n=pipe(pipefd);
    if(n==-1) return -1;

    pid_t id=fork();
    if(id==0) //child 进行写
    {
        close(pipefd[0]);
        Write(pipefd[1]);
        close(pipefd[1]);
        exit(1);
    }
    //father  进行读
    close(pipefd[1]);
    Read(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if(rid < 0) return 3;


    close(pipefd[0]);
    return 0;

}
